#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
报告生成器
生成各种格式的总结报告
"""

import json
import time
from pathlib import Path
from typing import List, Dict, Any
from ..utils import ensure_dir, ToolbeltLogger


class ReportGenerator:
    """报告生成器"""
    
    def __init__(self):
        """初始化报告生成器"""
        pass
    
    def generate_markdown_report(self, summaries: List[Dict[str, Any]], output_path: Path,
                                model: str, api_base: str, max_retries: int) -> None:
        """
        生成Markdown报告
        
        Args:
            summaries (List[Dict[str, Any]]): 总结数据列表
            output_path (Path): 输出文件路径
            model (str): 使用的模型名称
            api_base (str): API基础URL
            max_retries (int): 最大重试次数
        """
        ToolbeltLogger.info(f"生成Markdown报告: {output_path}")
        
        # 确保输出目录存在
        ensure_dir(output_path.parent)
        
        # 统计成功和失败的数量
        successful_count = sum(1 for s in summaries if s.get("success", True))
        failed_count = len(summaries) - successful_count
        
        # 计算总token消耗
        total_prompt_tokens = 0
        total_completion_tokens = 0
        total_tokens = 0
        
        for summary in summaries:
            if "token_usage" in summary:
                token_usage = summary["token_usage"]
                total_prompt_tokens += token_usage["prompt_tokens"]
                total_completion_tokens += token_usage["completion_tokens"]
                total_tokens += token_usage["total_tokens"]
        
        # 生成Markdown内容
        md_content = [
            "# PDF科技文献总结报告",
            "",
            f"生成时间: {time.strftime('%Y-%m-%d %H:%M:%S')}",
            f"处理文件数: {len(summaries)}",
            f"成功处理: {successful_count}",
            f"处理失败: {failed_count}",
            f"使用模型: {model}",
            f"API地址: {api_base or '默认Ollama本地服务'}",
            f"最大重试次数: {max_retries}",
        ]
        
        # 添加token消耗统计（如果有）
        if total_tokens > 0:
            md_content.extend([
                f"总提示token: {total_prompt_tokens}",
                f"总完成token: {total_completion_tokens}",
                f"总token: {total_tokens}",
            ])
        
        md_content.append("")
        md_content.append("---")
        md_content.append("")
        
        # 添加每个文献的总结
        for i, summary_data in enumerate(summaries, 1):
            status_icon = "✅" if summary_data.get("success", True) else "❌"
            md_content.extend([
                f"## {i}. {status_icon} {summary_data['filename']}",
                "",
                f"**文件路径**: {summary_data['filepath']}",
                "",
            ])
            
            md_content.extend([
                f"**文献总结**:",
                "",
                summary_data['summary'],
                ""
            ])
            
            # 添加token消耗信息（如果有）
            if "token_usage" in summary_data:
                token_usage = summary_data["token_usage"]
                md_content.extend([
                    f"**Token消耗**:",
                    f"- 提示token: {token_usage['prompt_tokens']}",
                    f"- 完成token: {token_usage['completion_tokens']}",
                    f"- 总token: {token_usage['total_tokens']}",
                    ""
                ])
            
            md_content.append("---")
            md_content.append("")
        
        # 写入文件
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write('\n'.join(md_content))
        
        ToolbeltLogger.info(f"报告已生成: {output_path}")
        
        # 打印总token消耗（如果有）
        if total_tokens > 0:
            ToolbeltLogger.info(f"\nToken消耗统计:")
            ToolbeltLogger.info(f"  总提示token: {total_prompt_tokens}")
            ToolbeltLogger.info(f"  总完成token: {total_completion_tokens}")
            ToolbeltLogger.info(f"  总token: {total_tokens}")
    
    def save_summaries_as_json(self, summaries: List[Dict[str, Any]], output_path: Path) -> None:
        """
        将总结结果保存为JSON格式
        
        Args:
            summaries (List[Dict[str, Any]]): 总结数据列表
            output_path (Path): 输出文件路径
        """
        ToolbeltLogger.info(f"保存JSON格式结果: {output_path}")
        
        # 确保输出目录存在
        ensure_dir(output_path.parent)
        
        # 写入JSON文件
        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(summaries, f, ensure_ascii=False, indent=2)
        
        ToolbeltLogger.info(f"JSON结果已保存: {output_path}")
    
    def save_summaries_as_txt(self, summaries: List[Dict[str, Any]], output_path: Path) -> None:
        """
        将总结结果保存为TXT格式
        
        Args:
            summaries (List[Dict[str, Any]]): 总结数据列表
            output_path (Path): 输出文件路径
        """
        ToolbeltLogger.info(f"保存TXT格式结果: {output_path}")
        
        # 确保输出目录存在
        ensure_dir(output_path.parent)
        
        # 生成TXT内容
        txt_content = []
        txt_content.append("PDF科技文献总结报告")
        txt_content.append("=" * 50)
        txt_content.append(f"生成时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
        txt_content.append(f"处理文件数: {len(summaries)}")
        txt_content.append("")
        
        # 添加每个文献的总结
        for i, summary_data in enumerate(summaries, 1):
            status = "成功" if summary_data.get("success", True) else "失败"
            txt_content.extend([
                f"{i}. {summary_data['filename']} [{status}]",
                f"   文件路径: {summary_data['filepath']}",
                f"   文献总结:",
                summary_data['summary'],
                ""
            ])
        
        # 写入文件
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write('\n'.join(txt_content))
        
        ToolbeltLogger.info(f"TXT结果已保存: {output_path}")